/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package zy.jpa;

import java.math.BigDecimal;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Hashtable;
import java.util.List;

import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.ejb.Remote;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.jms.BytesMessage;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSession;
import javax.jms.StreamMessage;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import zy.ejb.EJB3Factory;
import zy.ejb.HelloLocal;
import zy.ejb.HelloRemote;
import zy.ejb2.EJB2Factory;

/**
 *
 * @author Administrator
 */
@Stateless
@Remote(UserDAO.class)
public class UserDAOBean implements UserDAO {

	@PersistenceContext(unitName = "ejb1")
	protected EntityManager em;

	@Override
	public void batchInsertDemoDatas() {
		clearTableDemoDatas();
		long start = System.currentTimeMillis();
		int count = 500;
		for (int i = 0; i < count; i++) {

			User user = new User();
			user.setAvgWage(new BigDecimal(2500.25 + i * 10));
			user.setLoginDate(new Date(System.currentTimeMillis() + i * 24 * 60
					* 60 * 1000));
			user.setLoginTime(new Time(System.currentTimeMillis() + i * 24 * 60
					* 60 * 1000));
			user.setLoginDateTime(new Timestamp(System.currentTimeMillis() + i
					* 24 * 60 * 60 * 1000));
			user.setUserCode("TOM." + i);
			user.setUserName("汤姆." + i);
			user.setWorkYears(i + 1);
			em.persist(user);
		}
		System.out.println("批量插入数据" + count + "行，消耗时间="
				+ (System.currentTimeMillis() - start) + "毫秒,"
				+ (System.currentTimeMillis() - start) / 1000 + "秒");
	}

	@Override
	public List<User> getAllDatas() {
		long start = System.currentTimeMillis();
		// Query query = em.createQuery("from User order by id asc");
		Query query = em.createNativeQuery(
				"select * from User order by id asc", User.class);
		Object delgate = em.getDelegate();

		List list = query.getResultList();
		System.out.println("获取累计" + list.size() + "条记录，耗时"
				+ (System.currentTimeMillis() - start) / 1000
				+ "秒,delgate class=" + delgate.getClass());
		return list;
	}

	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public void clearTableDemoDatas() {
		long start = System.currentTimeMillis();
		Query query = em.createQuery("delete from User");
		int delCount = query.executeUpdate();
		System.out.println("删除全部数据，累计删除" + delCount + "行"
				+ (System.currentTimeMillis() - start) + "毫秒,");
	}

	@Override
	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public void batchInsertAsyDemoDatas() {

		// 增加测试ejb3内部获取本地home接口和remote接口
//		HelloRemote hello_Remote = (HelloRemote) EJB3Factory.getEJB_Local(
//				"Hello", HelloRemote.class);
//		System.out.print(hello_Remote.sayHello_remote("HELLO RemoteEJB3"));
//
//		HelloLocal hello_Local = (HelloLocal) EJB3Factory.getEJB_Local("Hello",
//				HelloLocal.class);
//		System.out.print(hello_Local.sayHello_local("HELLO Local EJB3"));
		EJB2Factory.demo_EJB2();
		System.out.print("HELLO Local EJB2");
		clearTableDemoDatas();
		long start = System.currentTimeMillis();
		int count = 5;
		for (int i = 0; i < count; i++) {

			User user = new User();
			user.setAvgWage(new BigDecimal(2500.25 + i * 10));
			user.setLoginDate(new Date(System.currentTimeMillis() + i * 24 * 60
					* 60 * 1000));
			user.setLoginTime(new Time(System.currentTimeMillis() + i * 24 * 60
					* 60 * 1000));
			user.setLoginDateTime(new Timestamp(System.currentTimeMillis() + i
					* 24 * 60 * 60 * 1000));
			user.setUserCode("asy_TOM." + i);
			user.setUserName("异步_汤姆." + i);
			user.setWorkYears(i + 1);
			em.persist(user);
		}

		System.out.println("batchInsertAsyDemoDatas()_批量插入数据" + count
				+ "行，消耗时间=" + (System.currentTimeMillis() - start) + "毫秒,"
				+ (System.currentTimeMillis() - start) / 1000 + "秒");

		sendOperMsg(count);
		if (true) {
			// 经过测试不能进行主动回滚
			// em.getTransaction().rollback();
			// throw new RuntimeException("主动异常，测试数据是否进入数据库");
		}

	}

	private void sendOperMsg(int count) {

		QueueConnection conn = null;
		QueueSession session = null;
		try {
			final Hashtable jndiProperties = new Hashtable();
			jndiProperties.put(Context.URL_PKG_PREFIXES,
					"org.jboss.ejb.client.naming");
			InitialContext ctx = new InitialContext(jndiProperties);
			QueueConnectionFactory factory = (QueueConnectionFactory) ctx
					.lookup("ConnectionFactory");
			conn = factory.createQueueConnection();
			session = conn.createQueueSession(false,
					QueueSession.AUTO_ACKNOWLEDGE);
			Destination destination = (Queue) ctx
					.lookup("java:/jms/queue/destination");
			MessageProducer producer = session.createProducer(destination);
			// 发送文本
			TextMessage msg = session
					.createTextMessage("创建操作User记录消息，本次操作新插入的记录数=" + count);
			producer.send(msg);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
		} finally {
			try {
				session.close();
				conn.close();
			} catch (JMSException e) {
				e.printStackTrace();
			}
		}
	}

}
